package com.qf.smartplatform.service.impl;

import com.qf.smartplatform.cache.SceneCache;
import com.qf.smartplatform.exceptions.AddDataException;
import com.qf.smartplatform.exceptions.ResultCode;
import com.qf.smartplatform.mapper.SceneMapper;
import com.qf.smartplatform.pojo.CheckType;
import com.qf.smartplatform.pojo.Scene;
import com.qf.smartplatform.pojo.User;
import com.qf.smartplatform.service.SceneService;
import com.qf.smartplatform.utils.SecurityUtils;
import com.sun.javafx.scene.SceneUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * projectName:day12_27_Test
 * author:guoLei
 * time:2022/1/4 14:43
 * description:
 */
@Service
@Transactional
public class SceneServiceImpl implements SceneService {
    private SceneMapper sceneMapper;
    private SceneCache sceneCache;
    @Autowired
    public void setSceneMapper(SceneMapper sceneMapper) {
        this.sceneMapper = sceneMapper;
    }
    @Autowired
    public void setSceneCache(SceneCache sceneCache) {
        this.sceneCache = sceneCache;
    }


    @Override
    public void addScene(Scene scene) {
        Assert.isTrue(!scene.isEmpty(CheckType.ADD),()->{
            throw new AddDataException("必须传递的数据不完整或，请检查", ResultCode.DATA_NULL);
        });
        User user= SecurityUtils.getUser();
        Scene scene1=sceneMapper.selectByUserIdAndName(user.getUId(),scene.getSceneName());
        Assert.isTrue(scene1==null||scene1.getStatus()!=1,()->{
            throw new AddDataException("场景已经存在", ResultCode.DATA_ALREADY_EXIST);
        });
        if (scene1 == null) {
            scene.setCreateBy(user.getUId());
            scene.setCreateTime(new Date());
            sceneMapper.addScene(scene);
        }else {
            scene1.setCreateTime(new Date());
            sceneMapper.reEnableScene(scene1.getSceneId(),new Date());
        }
    }

    @Override
    public void updateScene(Scene scene) {
        Assert.isTrue(!scene.isEmpty(CheckType.UPDATE),()->{
            throw new AddDataException("必须传递的数据不完整,请检查", ResultCode.DATA_NULL);
        });
        sceneMapper.updateScene(scene);
    }

    @Override
    public void deleteByIds(List<Long> ids, Long userId) {

    }

    @Override
    public List<Scene> findByUserId(Long userId) {
        try {
            List<Scene> sceneList = sceneCache.getSceneLoadingCache().get(userId);//通过缓存获取数据
            return sceneList;
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
